use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use tracing::{debug, error};
use crate::http::http_request::HttpRequest;
use crate::http::http_response::HttpResponse;

pub fn static_handler(request: &HttpRequest, response: &mut HttpResponse) {
     // 获取请求的文件路径并清理
     let file_path = request.uri.as_str().trim_start_matches('/');



     // 安全检查：防止目录遍历
     if file_path.contains("..") {
         HttpResponse::forbidden(response);
     }
     
     let full_path = Path::new("public/resources/").join(file_path);
     debug!("full_path : {}", full_path.display());


     // 检查文件是否存在
     if !full_path.exists() || !full_path.is_file() {
         return HttpResponse::not_found(response);
     }
 
     // 获取文件的 MIME 类型
     let content_type = get_content_type(&full_path);
 
    // 读取文件内容
    let file = match File::open(&full_path) {
        Ok(file) => file,
        Err(e) => {
            error!("Failed to read file: {}", e);
            HttpResponse::server_error(response);
            return;
        },
    };

    
    // 使用 BufReader 提高读取效率
    let mut reader = BufReader::new(file);

        // 根据内容类型选择不同的处理方式
    if content_type.starts_with("text/") || content_type == "application/javascript" {
        // 文本文件处理
        let mut content = String::new();
        if let Err(e) = reader.read_to_string(&mut content) {
            error!("Failed to read file: {}", e);
            HttpResponse::server_error(response);
        }
        let mut headers = &mut response.headers;
        HttpResponse::common_headers(headers);
        headers.insert("Content-Type".to_string(), content_type.to_string());
        headers.insert("Content-Length".to_string(), content.len().to_string());
        headers.insert("Cache-Control".to_string(), "public, max-age=31536000, immutable".to_string());
        response.body = content.into_bytes();
        HttpResponse::ok(response);
    } else {
        // 二进制文件处理
        let mut content = Vec::new();
        if let Err(e) = reader.read_to_end(&mut content) {
            error!("Failed to read file: {}", e);
            HttpResponse::server_error(response);
        }

        debug!("content : {:?}", content.len());

        let mut headers = &mut response.headers;
        HttpResponse::common_headers(headers);
        headers.insert("Content-Type".to_string(), content_type.to_string());
        headers.insert("Content-Length".to_string(), content.len().to_string());
        headers.insert("Cache-Control".to_string(), "public, max-age=31536000, immutable".to_string());
        response.body = content;
        HttpResponse::ok(response);
    }

}


// 添加 MIME 类型判断函数
fn get_content_type(path: &Path) -> &'static str {
    match path.extension()
        .and_then(|ext| ext.to_str())
        .map(|s| s.to_lowercase())
        .as_deref() {
            Some("html") => "text/html",
            Some("css") => "text/css",
            Some("js") => "application/javascript",
            Some("png") => "image/png",
            Some("jpg") | Some("jpeg") => "image/jpeg",
            Some("gif") => "image/gif",
            Some("svg") => "image/svg+xml",
            Some("ico") => "image/x-icon",
            _ => "application/octet-stream",
    }
}